package September20;

public class NumberToChinese {
    public static void main(String[] args) {
        // 示例输入
        int number = 3004;
        String chineseNumber = convertToChinese(number);
        System.out.println("数字 " + number + " 的中文读法是：" + chineseNumber);
    }

    public static String convertToChinese(int number) {
        if (number == 0) {
            return "零";
        }

        String[] chineseNumbers = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        String[] units = {"", "十", "百", "千"};
        String[] sections = {"", "万", "亿", "万亿"};

        StringBuilder result = new StringBuilder();
        int section = 0; // 表示当前是哪一个大的数位区段

        while (number > 0) {
            int current = number % 10000; // 取当前区段的数字
            if (current == 0) {
                section++;
                number /= 10000;
                continue;
            }

            StringBuilder sectionResult = new StringBuilder();
            int unitIndex = 0;
            while (current > 0) {
                int digit = current % 10;
                if (digit == 0) {
                    if (sectionResult.length() > 0 && sectionResult.charAt(0) != '零') {
                        sectionResult.insert(0, "零");
                    }
                } else {
                    sectionResult.insert(0, chineseNumbers[digit] + units[unitIndex]);
                }
                current /= 10;
                unitIndex++;
            }

            if (sectionResult.length() > 0 && sectionResult.charAt(0) == '零') {
                sectionResult.deleteCharAt(0); // 删除千位、百位、十位的前导零
            }
            if (section > 0) {
                sectionResult.append(sections[section]); // 加上万、亿等
            }

            result.insert(0, sectionResult);
            number /= 10000;
            section++;
        }

        return result.toString();
    }
}
